package com.cskaoyan.service.impl;

import com.cskaoyan.bean.bo.OrderRefundBO;
import com.cskaoyan.bean.bo.OrderReplyBO;
import com.cskaoyan.bean.bo.OrderShipBO;
import com.cskaoyan.bean.param.BaseParam;
import com.cskaoyan.bean.pojo.*;
import com.cskaoyan.bean.vo.OrderChannelVO;
import com.cskaoyan.bean.vo.OrderDetailVO;
import com.cskaoyan.bean.vo.OrderListVO;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.OrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import static com.cskaoyan.util.Constant.channelMap;

/**
 * @author rebaogu
 * @description 订单实现类
 * @date 2022.04.06 23:19
 * @package com.cskaoyan.service
 * @Classname OrderServiceImpl
 */
@Service
public class OrderServiceImpl implements OrderService {

    // 订单
    @Autowired
    MarketOrderMapper marketOrderMapper;

    // 订单商品
    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;

    // 用户
    @Autowired
    MarketUserMapper marketUserMapper;

    // 评论
    @Autowired
    MarketCommentMapper marketCommentMapper;

    //
    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;

    @Autowired
    MarketGoodsMapper marketGoodsMapper;


    @Override
    public OrderListVO orderList(BaseParam param, Short orderStatusArray, Integer orderId, Date start, Date end, Integer userId, String orderSn) {

        // 获取分页相关信息
        Integer page = param.getPage();
        Integer limit = param.getLimit();
        String sort = param.getSort();
        String order = param.getOrder();

        // 开启分页
        PageHelper.startPage(page, limit);

        MarketOrderExample example = new MarketOrderExample();
        // 拼接排序依据：sort和order
        example.setOrderByClause(sort + " " + order);

        MarketOrderExample.Criteria criteria = example.createCriteria();
        // 需要判断当前deteid是否为1
        // true --> 已经删除  false --> 未被删除
        criteria.andDeletedEqualTo(false);

        // 动态拼接
        if (orderId != null && "".equals(orderId)) {
            criteria.andIdEqualTo(orderId);
        } else {
            if (orderStatusArray != null && "".equals(orderStatusArray)) {
                criteria.andOrderStatusEqualTo(orderStatusArray);
            }
            if (start != null && "".equals(start)) {
                criteria.andShipTimeGreaterThanOrEqualTo(start);
            }
            if (end != null && "".equals(end)) {
                criteria.andEndTimeLessThanOrEqualTo(end);
            }
            if (userId != null && "".equals(userId)) {
                criteria.andUserIdEqualTo(userId);
            }
            if (orderSn != null && "".equals(orderSn)) {
                criteria.andOrderSnEqualTo(orderSn);
            }
        }

        // 查询
        List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(example);

        // 插件获取分页信息
        PageInfo<MarketOrder> pageInfo = new PageInfo<>(marketOrders);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();

        OrderListVO orderListVO = new OrderListVO((int) total, pages, limit, page, marketOrders);

        return orderListVO;
    }

    @Override
    public List<OrderChannelVO> orderChannel() {

        OrderChannelVO orderChannelVO = new OrderChannelVO();

        List<OrderChannelVO> orderChannelVOList = new ArrayList<>();

        // 遍历 Map
        Iterator<Map.Entry<String, String>> entries = channelMap.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, String> entry = entries.next();
            String key = entry.getKey();
            String value = entry.getValue();
            orderChannelVOList.add(new OrderChannelVO(key, value));
        }
        return orderChannelVOList;
    }

    @Override
    public void orderDelete(Integer orderId) {
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        marketOrder.setDeleted(true);
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        marketOrderMapper.updateByExampleSelective(marketOrder, marketOrderExample);
    }

    @Override
    public OrderDetailVO orderDetail(Integer orderId) {

        OrderDetailVO orderDetailVO = new OrderDetailVO();

        // 1, 根据orderid 查询, 获取marketOrdergoods所有的信息,封装成一个list

        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = marketOrderGoodsExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);


        // 2, 根据orderid 找到userid 通过userid 找到nickname 和 avatar(用户留言)

        MarketOrderExample example2SelectUserId = new MarketOrderExample();
        MarketOrderExample.Criteria criteria2SelectUserId = example2SelectUserId.createCriteria();
        criteria2SelectUserId.andIdEqualTo(orderId);
        List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(example2SelectUserId);

        Integer userId = 0;
        for (MarketOrder marketOrder : marketOrders) {
            userId = marketOrder.getUserId();
        }

        // 根据 userid获取nickname 和 avatar(用户留言)
        MarketUserExample marketUserExample = new MarketUserExample();
        MarketUserExample.Criteria criteria2User = marketUserExample.createCriteria();
        criteria2User.andIdEqualTo(userId);
        List<MarketUser> marketUsers = marketUserMapper.selectByExample(marketUserExample);

        OrderDetailVO.UserDTO userDTO = new OrderDetailVO.UserDTO();
        for (MarketUser marketUser : marketUsers) {
            userDTO.setNickname(marketUser.getNickname());
            userDTO.setAvatar(marketUser.getAvatar());
        }

        OrderDetailVO.OrderDTO orderDTO = null;
        // 3, 根据订单id 找到对应的数据,封装进该对象返回出去
        for (MarketOrder marketOrder : marketOrders) {
            orderDTO = new OrderDetailVO.OrderDTO(
                    marketOrder.getId()
                    , marketOrder.getUserId()
                    , marketOrder.getOrderSn()
                    , marketOrder.getOrderStatus()
                    , marketOrder.getAftersaleStatus()
                    , marketOrder.getConsignee()
                    , marketOrder.getMobile()
                    , marketOrder.getAddress()
                    , marketOrder.getMessage()
                    , marketOrder.getGoodsPrice()
                    , marketOrder.getFreightPrice()
                    , marketOrder.getCouponPrice()
                    , marketOrder.getIntegralPrice()
                    , marketOrder.getGrouponPrice()
                    , marketOrder.getOrderPrice()
                    , marketOrder.getActualPrice()
                    , marketOrder.getComments()
                    , String.valueOf(marketOrder.getEndTime())
                    , String.valueOf(marketOrder.getAddTime())
                    , String.valueOf(new Date())
                    , marketOrder.getDeleted()
            );
        }

        // 4, 最后将三个数据封装 返回
        orderDetailVO.setOrderGoods(marketOrderGoods);
        orderDetailVO.setUser(marketUsers.get(0));
        orderDetailVO.setOrder(marketOrders.get(0));

        return orderDetailVO;
    }

    @Override
    public int orderReply(OrderReplyBO orderReplyBO) {
        Integer commentId = orderReplyBO.getCommentId();
        String content = orderReplyBO.getContent();
        // 根据id 查找comment对象
        MarketCommentExample example = new MarketCommentExample();
        MarketCommentExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(commentId);

        List<MarketComment> marketComments = marketCommentMapper.selectByExample(example);

        // set comment对象
        MarketComment marketComment = marketComments.get(0);
        // 如果非空
        if (marketComment.getAdminContent() == null || "".equals(marketComment.getAdminContent())) {
            marketComment.setAdminContent(content);
            // 更新
            marketCommentMapper.updateByExampleSelective(marketComment, example);
            return 200;
        } else {// 已经回复
            return 500;
        }
    }


    @Override
    public int orderRefund(OrderRefundBO orderRefundBO) {

        // 直接退库存量到 goods 表


        Integer orderId = orderRefundBO.getOrderId();
        BigDecimal refundMoney = orderRefundBO.getRefundMoney();

        MarketOrderExample example = new MarketOrderExample();

        MarketOrderExample.Criteria criteria = example.createCriteria();

        criteria.andIdEqualTo(orderId);

        List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(example);

        for (MarketOrder marketOrder : marketOrders) {
            // 1,首先修改变量
            if (marketOrder.getAftersaleStatus() >= 3) {
                return 500;
            }
            marketOrder.setRefundAmount(refundMoney);
            marketOrder.setOrderStatus((short) 203);
            marketOrder.setAftersaleStatus((short) 3);
            marketOrder.setRefundTime(new Date());
            marketOrder.setUpdateTime(new Date());
            marketOrderMapper.updateByExampleSelective(marketOrder, example);

            // 2, 退库存量到goods表 订单id --> goodsid 列表
            Integer orderId1 = marketOrder.getId();
            MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
            MarketOrderGoodsExample.Criteria goodsExampleCriteria = orderGoodsExample.createCriteria();
            goodsExampleCriteria.andGoodsIdEqualTo(orderId1).andDeletedEqualTo(false);

            List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(orderGoodsExample);

            for (MarketOrderGoods marketOrderGood : marketOrderGoods) {
                // 获取 订单号一样的  productid
                Integer goodsCount = Integer.valueOf(marketOrderGood.getNumber());
                Integer productId = marketOrderGood.getProductId();

                // List<MarketGoodsProduct> productArrayList = new ArrayList<>();
                MarketGoodsProductExample productExample = new MarketGoodsProductExample();
                MarketGoodsProductExample.Criteria productCriteria = productExample.createCriteria();
                productCriteria.andDeletedEqualTo(false).andIdEqualTo(productId);

                List<MarketGoodsProduct> marketGoodsProducts = marketGoodsProductMapper.selectByExample(productExample);
                if (marketGoodsProducts != null && marketGoodsProducts.size() == 1) {
                    for (MarketGoodsProduct goodsProduct : marketGoodsProducts) {
                        // 获取库存
                        Integer number = goodsProduct.getNumber();
                        // 减少 多少个 库存
                        goodsProduct.setNumber(number + goodsCount);
                        goodsProduct.setUpdateTime(new Date());
                        marketGoodsProductMapper.updateByPrimaryKey(goodsProduct);
                    }
                }

            }
        }
        return 200;
    }

    @Override
    public int orderShip(OrderShipBO orderShipBO) {

        Integer orderId = orderShipBO.getOrderId();
        String shipChannel = orderShipBO.getShipChannel();
        String shipSn = orderShipBO.getShipSn();

        // 通过key获取 快递对应的名称
        MarketOrder marketOrder1 = new MarketOrder();
        String refundContent = channelMap.get(shipChannel);

        MarketOrderExample example = new MarketOrderExample();

        MarketOrderExample.Criteria criteria = example.createCriteria();

        criteria.andIdEqualTo(orderId).andDeletedEqualTo(false);

        List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(example);

        for (MarketOrder marketOrder : marketOrders) {
            if (marketOrder.getAftersaleStatus() >= 3) {
                return 500;
            }

            marketOrder.setOrderStatus((short) 301);
            marketOrder.setAftersaleStatus((short) 0);

            marketOrder.setShipChannel(shipChannel);
            marketOrder.setShipSn(shipSn);
            marketOrder.setRefundContent(refundContent);
            marketOrder.setShipTime(new Date());
            marketOrderMapper.updateByExampleSelective(marketOrder, example);
        }
        return 200;
    }


}
